from datetime import datetime
import sys
from PySide6.QtWidgets import (QApplication, QDialog, QFileDialog, QTableWidgetItem, 
                             QLabel, QLineEdit, QPushButton, QVBoxLayout, QHBoxLayout, QFormLayout,
                             QWidget, QMessageBox, QComboBox, QHeaderView,QDialogButtonBox)
from PySide6.QtCore import Qt, QDate, QTime, QDateTime, QPoint, QEvent,Signal
from PySide6.QtNetwork import QNetworkAccessManager, QNetworkRequest, QNetworkReply
from PySide6.QtGui import QGuiApplication
from gui.utils.api import API
from gui.window.DateTimeRange import DateTimeRangeEdit
from gui.window.child_dialog.base_manager import TableWidget_Base_Datamanager

def timestamp_to_string(timestamp, format='%Y-%m-%d %H:%M:%S'):
    """
    把时间戳转换为字符串
    :param timestamp: 时间戳（可以是int、float类型）
    :param format: 输出的字符串格式，默认是 '%Y-%m-%d %H:%M:%S'
    :return: 格式化后的时间字符串
    """
    # 把时间戳转换为datetime对象
    dt_object = datetime.fromtimestamp(timestamp)
    # 按照指定格式把datetime对象格式化为字符串
    return dt_object.strftime(format)

class DatasetForm(QDialog):
    """数据集表单对话框"""
    def __init__(self, dataset=None, parent=None):
        super().__init__(parent)
        self.setWindowTitle("数据集信息" + (" - 编辑" if dataset else " - 添加"))
        self.resize(400, 300)
        
        self.dataset = dataset or {}
        
        layout = QVBoxLayout(self)
        form_layout = QFormLayout()
        
        self.name_edit = QLineEdit(self.dataset.get("name", ""))
        self.desc_edit = QLineEdit(self.dataset.get("desc", ""))
        
        self.type_combo = QComboBox()
        self.type_combo.addItems(["图片", "视频", "音频"])
        current_type = self.dataset.get("data_type")
        if current_type:
            type_index = {"1": 0, "2": 1, "3": 2}.get(current_type, 0)
            self.type_combo.setCurrentIndex(type_index)
        if dataset:
            self.name_edit.setReadOnly(True)
            self.desc_edit.setReadOnly(True)
            self.type_combo.setEnabled(False)
        
        # 2. 文件选择
        file_layout = QHBoxLayout()
        self.file_path_edit = QLineEdit()
        self.file_path_edit.setReadOnly(True)  # 只读，只能通过选择按钮设置
        self.select_file_btn = QPushButton("选择文件")
        self.select_file_btn.clicked.connect(self.select_file)
        file_layout.addWidget(self.file_path_edit)
        file_layout.addWidget(self.select_file_btn)
        self.file_count_edit = QLineEdit(str(self.dataset.get("file_count", "")))
        
        form_layout.addRow("名称:", self.name_edit)
        form_layout.addRow("描述:", self.desc_edit)
        form_layout.addRow("类型:", self.type_combo)
        form_layout.addRow("文件:", file_layout)
        
        layout.addLayout(form_layout)
        
        # 按钮
        button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        button_box.accepted.connect(self.accept)
        button_box.rejected.connect(self.reject)
        layout.addWidget(button_box)
    
    def select_file(self):
        """选择文件（支持图片、视频、zip）"""
        # 支持的文件类型过滤
        file_filter = (
            # "图片文件 (*.jpg *.jpeg *.png);;"
            # "视频文件 (*.mp4 *.avi *.mov);;"
            "压缩包 (*.zip);;"
            # "所有支持的文件 (*.jpg *.jpeg *.png *.mp4 *.avi *.mov *.zip)"
        )
        # 打开文件选择对话框
        file_path, _ = QFileDialog.getOpenFileName(
            self, "选择要上传的文件", QGuiApplication.applicationDirPath(), file_filter
        )
        if file_path:
            self.file_path = file_path
            self.file_path_edit.setText(file_path)
            # self.check_uploadable()  # 检查是否可上传
            
    def get_data(self):
        """获取表单数据"""
        data = {
            "name": self.name_edit.text(),
            "desc": self.desc_edit.text(),
            "data_type": str(self.type_combo.currentIndex() + 1),
            "file_path": self.file_path
        }
        
        if self.dataset:  # 编辑模式
            data["id"] = self.dataset.get("id")
        return data

class TableWidget_Datasets_manager(TableWidget_Base_Datamanager):
    def __init__(self, api: API):
        super().__init__(api)
        self.setWindowTitle("数据集管理系统")
        self.resize(1000, 600)
        self.set_table_columns(["ID", "名称", "描述", "类型", "文件数量", "创建时间", "结束时间", "操作"])
    
    def setup_top_buttons(self):
        """设置顶部按钮"""
        self.add_button = QPushButton("添加数据集")
        self.add_button.clicked.connect(self.add_dataset)
        self.top_button_layout.addStretch()
        self.top_button_layout.addWidget(self.add_button)
    
    
    def setup_search_fields(self):
        """设置搜索字段"""
        # 搜索框
        self.search_name_field = QLineEdit()
        self.search_name_field.setPlaceholderText("输入数据库名称...")
        
        self.search_decs_field = QLineEdit()
        self.search_decs_field.setPlaceholderText("输入数据库描述...")
        
        self.search_file_type_field = QComboBox()
        self.search_file_type_field.setPlaceholderText("选择数据类型...")
        self.search_file_type_field.addItems(["", "图片", "视频", "音频"])
        
        
        # 添加到搜索布局
        self.search_h1_layout.addWidget(self.search_name_field)
        self.search_h1_layout.addWidget(self.search_decs_field)
        self.search_h1_layout.addWidget(self.search_file_type_field)
        

    def fill_table_row(self, row, item):
        """填充数据集表格行数据"""
        data_type = {"1": "图片", "2": "视频", "3": "音频"}.get(item["data_type"], "图片")
        
        id_item = QTableWidgetItem(str(item["id"]))
        id_item.setData(Qt.ItemDataRole.UserRole, item)
        self.table.setItem(row, 0, id_item)
        
        self.table.setItem(row, 1, QTableWidgetItem(item["name"]))
        self.table.setItem(row, 2, QTableWidgetItem(item["desc"]))
        self.table.setItem(row, 3, QTableWidgetItem(data_type))
        self.table.setItem(row, 4, QTableWidgetItem(str(item["file_count"])))
        self.table.setItem(row, 5, QTableWidgetItem(timestamp_to_string(item["create_at"])))
        self.table.setItem(row, 6, QTableWidgetItem(timestamp_to_string(item["update_at"])))
        
        # 操作按钮
        edit_button = QPushButton("编辑")
        edit_button.clicked.connect(lambda checked, r=row: self.edit_dataset(r))
        delete_button = QPushButton("删除")
        delete_button.clicked.connect(lambda checked, r=row: self.delete_dataset(r))
        
        button_widget = QWidget()
        button_layout = QHBoxLayout(button_widget)
        button_layout.addWidget(edit_button)
        button_layout.addWidget(delete_button)
        button_layout.setContentsMargins(0, 0, 0, 0)
        self.table.setCellWidget(row, 7, button_widget)
    
    def get_query_params(self):
        """获取查询参数"""
        params = super().get_query_params()
        
        search_name_field_text = self.search_name_field.text().strip()
        search_decs_field_text = self.search_decs_field.text().strip()
        search_file_type_field_text = self.search_file_type_field.currentText()
        search_create_start_datetime, search_create_end_datetime = self.search_create_field.get_range()
        search_update_start_datetime, search_update_end_datetime = self.search_update_field.get_range()
        search_file_type_field_text = {"图片": 1, "视频": 2, "音频": 3}.get(search_file_type_field_text, "")
        
        params.update({
            "name": search_name_field_text,
            "desc": search_decs_field_text,
            "data_type": search_file_type_field_text,
            "create_at": [search_create_start_datetime, search_create_end_datetime],
            "update_at": [search_update_start_datetime, search_update_end_datetime],
        })
        
        return params
    
    
    def load_data(self):
        """加载数据集数据"""
        query_params = self.get_query_params()
        self.api.query_datasets(**query_params, callback=self.update_table)
    
    def add_dataset(self):
        """添加数据集"""
        dialog = DatasetForm(parent=self)
        def callback(result):
            dataset_id = result.get("id")
            self.api.attach_file_datasets(dataset_id=dataset_id,file_path=file_path, callback=self.on_add_success)
            
        if dialog.exec():
            data = dialog.get_data()
            file_path = data.pop("file_path")
            self.api.add_dataset(**data, callback=callback)
    
    def update_upload_progress(self, bytes_sent, bytes_total):
        """更新上传进度"""
        if bytes_total > 0:
            progress = int((bytes_sent / bytes_total) * 100)
            print(f"上传中：{progress}% （{bytes_sent}/{bytes_total}字节）")
            # self.progress_bar.setValue(progress)
            # self.status_label.setText(f"上传中：{progress}% （{bytes_sent}/{bytes_total}字节）")

    def handle_upload_finished(self, reply :QNetworkReply):
        """处理上传完成（无论成功失败）"""
        # if reply != self.upload_reply:
        #     return  # 忽略非当前上传的回复

        # 读取响应数据
        try:
            response_data = reply.readAll().data().decode('utf-8')
            status_code = reply.attribute(QNetworkRequest.Attribute.HttpStatusCodeAttribute)
            
            if status_code == 200:
                self.status_label.setText("上传成功！")
                QMessageBox.information(self, "成功", f"文件上传成功\n响应：{response_data}")
            else:
                self.status_label.setText(f"上传失败（状态码：{status_code}）")
                QMessageBox.warning(self, "失败", f"上传失败\n状态码：{status_code}\n响应：{response_data}")
        except Exception as e:
            self.status_label.setText(f"处理响应失败：{str(e)}")
            QMessageBox.critical(self, "响应错误", f"无法解析服务器响应：{str(e)}")

        # # 清理
        # self.upload_reply = None
        # self.progress_bar.setValue(0)
        # self.upload_btn.setEnabled(True)  # 恢复按钮可用
        
    def on_add_success(self, response):
        """添加成功回调"""
        if response.get("code") == 0:
            QMessageBox.information(self, "成功", "数据集添加成功")
            self.load_data()
        else:
            QMessageBox.critical(self, "失败", f"数据集添加失败: {response.get('message', '未知错误')}")
    
    def edit_dataset(self, row):
        """编辑数据集"""
        item = self.table.item(row, 0).data(Qt.ItemDataRole.UserRole)
        dialog = DatasetForm(item, parent=self)
        if dialog.exec():
            data = dialog.get_data()
            dataset_id = data.get("id")
            file_path = data.get("file_path")
            self.api.attach_file_datasets(dataset_id=dataset_id,file_path=file_path, callback=self.on_add_success)
            # self.api.update_dataset(**data, callback=self.on_edit_success)
    
    def on_edit_success(self, response):
        """编辑成功回调"""
        if response.get("code") == 0:
            QMessageBox.information(self, "成功", "数据集更新成功")
            self.load_data()
        else:
            QMessageBox.critical(self, "失败", f"数据集更新失败: {response.get('message', '未知错误')}")
    
    def delete_dataset(self, row):
        """删除数据集"""
        item = self.table.item(row, 0).data(Qt.ItemDataRole.UserRole)
        reply = QMessageBox.question(
            self, "确认删除", 
            f"确定要删除数据集 '{item['name']}' 吗？",
            QMessageBox.Yes | QMessageBox.No
        )
        if reply == QMessageBox.Yes:
            self.api.del_dataset(dataset_id=item["id"], callback=self.on_delete_success)
            print(item)
    
    def on_delete_success(self, response):
        """删除成功回调"""
        if response.get("code") == 0:
            QMessageBox.information(self, "成功", "数据集删除成功")
            self.load_data()
        else:
            QMessageBox.critical(self, "失败", f"数据集删除失败: {response.get('message', '未知错误')}")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = TableWidget_Datamanager()
    window.show()
    sys.exit(app.exec())